package com.caration.shell.preference;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.preference.Preference;

import com.caration.sdk.utilities.DataUtils;
import com.caration.shell.R;
import com.caration.shell.config.CommonConfig;
import com.caration.shell.cr3d.SharedData;

public final class SettingScreenOrientPreference {
	private static int sLastOrient;
	private static int sOrient;

	static int getOrient() {
		return sOrient;
	}

	static int getLastOrient() {
		return sLastOrient;
	}

	static void setOrientation(int orient) {
		sOrient = orient;
	}

	static void init(Preference preference) {
		setSummary(preference);
	}

	static void show(Context context, final Preference preference) {
		android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
				context);
		builder.setTitle(R.string.mn_screen_orientation);
		String orientation = getDefaultOrientation();

		String array[] = new String[3];
		array[0] = orientation;
		array[1] = DataUtils.getString(SharedData.getContext(),
				R.string.mn_orientation_portrait);
		array[2] = DataUtils.getString(SharedData.getContext(),
				R.string.mn_orientation_landscape);
		sOrient = sLastOrient = CommonConfig.getScreenOrientation();
		builder.setSingleChoiceItems(array, sOrient, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				setOrientation(which);
			}
		});
		builder.setPositiveButton(R.string.public_action_ok,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (getOrient() != getLastOrient()) {
							CommonConfig.setScreenOrient(getOrient());
							setSummary(preference);
						}
					}
				});
		builder.setNegativeButton(R.string.public_action_cancel, null);
		builder.create().show();
	}

	static void setSummary(Preference preference) {
		switch (CommonConfig.getScreenOrientation()) {
		case 0:
			preference.setSummary(getDefaultOrientation());
			break;

		case 1:
			preference
					.setSummary(DataUtils.getString(SharedData.getContext(),
							R.string.mn_orientation_portrait));
			break;

		case 2:
			preference.setSummary(DataUtils.getString(
					SharedData.getContext(),
					R.string.mn_orientation_landscape));
			break;
		}
	}

	static String getDefaultOrientation() {
		String str = DataUtils
				.getString(
						SharedData.getContext(),
						SharedData.getContext().getResources()
								.getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE ? R.string.mn_orientation_portrait
								: R.string.mn_orientation_landscape);
		return new StringBuilder(DataUtils.getString(SharedData.getContext(),
				R.string.mn_orientation_system)).append("(").append(str)
				.append(")").toString();
	}
}
